//
//  AppDelegate.m
//  Telemedicine
//
//  Created by Trong Ton on 5/12/14.
//  Copyright (c) 2014 Trong Ton. All rights reserved.
//

#import "AppDelegate.h"
#import "HomePageViewController.h"
#import "CallDoctorViewController.h"
#import "HelpCenterViewController.h"
#import "AHAHViewController.h"
#import "LoadingViewController.h"
#import "Reachability.h"

#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@implementation AppDelegate

@synthesize isNetworkAvailable;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
//    [[baseTabBarController tabBar] setSelectionIndicatorImage:[UIImage imageNamed:@"tab-background-selected.jpg"]];

//    [[baseTabBarController.tabBar.items objectAtIndex:0] setImage:[UIImage imageNamed:@"Home.png"] forState:UIControlStateNormal];
//    [baseTabBarController setToolbarItems:tabItems];
    LoadingViewController *aVC = [[[LoadingViewController alloc] init] autorelease];
    [self registerToGetNetWorkStatus];
    
    if( [UIDevice instancesRespondToSelector:@selector(identifierForVendor)] ) {
        NSUUID *oNSUUID = [[UIDevice currentDevice] identifierForVendor];
        self.deviceUUID = [oNSUUID UUIDString];
    }
    else {
        self.deviceUUID = [self getMacAddress];
    }
    
    [self clearNotifications];
    
//    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)];
    }
    
    BOOL wasLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"wasLogin"];
    if(wasLogin) {
        [self updateNotifyWhenChangeStatusLogin];
    }
    
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = aVC;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [self clearNotifications];
    BOOL wasLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"wasLogin"];
    if(wasLogin) {
        [self updateNotifyWhenChangeStatusLogin];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    if([firstView isKindOfClass:[CallDoctorViewController class]]) {
//        CallDoctorViewController *view = (CallDoctorViewController *)firstView;
//        [view checkEnableCallDoctor];
//    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    size_t              length;
    unsigned char       macAddress[6];
    struct if_msghdr    *interfaceMsgStruct;
    struct sockaddr_dl  *socketStruct;
    NSString            *errorFlag = NULL;
    
    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces
    
    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    else
    {
        // Get the size of the data available (store in len)
        if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
            errorFlag = @"sysctl mgmtInfoBase failure";
        else
        {
            // Alloc memory based on above call
            if ((msgBuffer = malloc(length)) == NULL)
                errorFlag = @"buffer allocation failure";
            else
            {
                // Get system information, store in buffer
                if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
                    errorFlag = @"sysctl msgBuffer failure";
            }
        }
    }
    
    // Befor going any further...
    if (errorFlag != NULL)
    {
        //        NSLog(@"Error: %@", errorFlag);
        return errorFlag;
    }
    
    // Map msgbuffer to interface message structure
    interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
    
    // Map to link-level socket structure
    socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
    
    // Copy link layer address data in socket structure to an array
    memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
    
    // Read from char array into a string object, into traditional Mac address format
    NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                  macAddress[0], macAddress[1], macAddress[2],
                                  macAddress[3], macAddress[4], macAddress[5]];
    //    NSLog(@"Mac Address: %@", macAddressString);
    
    // Release the buffer memory
    free(msgBuffer);
    
    return macAddressString;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken  {
    
    NSString* newToken = [deviceToken description];
    
    newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    
    newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //kUrlSendDeviceInstall
    NSString *deviceTokenSave = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceTokenSave"];
    if (!deviceTokenSave || deviceTokenSave.length == 0) {
        [[NSUserDefaults standardUserDefaults] setObject:newToken forKey:@"DeviceTokenSave"];
    }
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
        NSLog(@"%@", [err description]);
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}

//For interactive notification only
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
{
    //handle the actions
    if ([identifier isEqualToString:@"declineAction"]){
    }
    else if ([identifier isEqualToString:@"answerAction"]){
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)_userInfo {
    
}

- (void)clearNotifications {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

- (void)updateNotifyWhenChangeStatusLogin {
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceTokenSave"];
    if (self.deviceUUID && ![self.deviceUUID isEqualToString:@""] && deviceToken && ![deviceToken isEqualToString:@""]) {
        if([AppDelegate sharedDelegate].isNetworkAvailable) {
            NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
            
            APIsBaseService *serVice = [APIsBaseService service];
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setObject:deviceToken forKey:@"token"];
            [param setObject:codeString forKey:@"code"];
            [param setObject:@"IOS" forKey:@"type"];
            
            [serVice requestWithURL:kCheckCodeValidate
                             params:param
                       successBlock:^(NSDictionary *dictionary){
                           NSLog(@"dic = %@", [dictionary description]);
                       }
                         errorBlock:^(NSError *error){
                         }
                         httpMethod:@"GET"];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
    }
}

+ (AppDelegate *)sharedDelegate {
    return (AppDelegate *) [UIApplication sharedApplication].delegate;
}

- (void)addCallDoctorView {
    if (self.window.rootViewController) {
        self.window.rootViewController = nil;
    }
//    UITabBarController *baseTabBarController = [[[UITabBarController alloc]init] autorelease];
//    
//    CallDoctorViewController *callView = [[[CallDoctorViewController alloc] init] autorelease];
//    HelpCenterViewController *helpView = [[[HelpCenterViewController alloc] init] autorelease];
//    AHAHViewController *partnerView = [[[AHAHViewController alloc] init] autorelease];
//    
//    UITabBarItem *tabCall = [[[UITabBarItem alloc] initWithTitle:@"CALL DOCTOR" image:[UIImage imageNamed:@"ico-tab-call.png"] tag:0] autorelease];
//    UITabBarItem *tabHelp = [[[UITabBarItem alloc] initWithTitle:@"HELP CENTER" image:[UIImage imageNamed:@"ico-tab-help.png"] tag:1] autorelease];
//    UITabBarItem *tabPartners = [[[UITabBarItem alloc] initWithTitle:@"AHAH" image:[UIImage imageNamed:@"ico-tab-AHAH.png"] tag:2] autorelease];
//    NSArray *controllers = [NSArray arrayWithObjects:callView,helpView, partnerView, nil];
//
//    callView.tabBarItem = tabCall;
//    helpView.tabBarItem = tabHelp;
//    partnerView.tabBarItem = tabPartners;
//    
//    baseTabBarController.viewControllers = controllers;
//    
//    [[baseTabBarController tabBar] setBackgroundImage:[UIImage imageNamed:@"tab-background.jpg"]];
//    [[baseTabBarController tabBar] setSelectionIndicatorImage:[UIImage imageNamed:@"tab-background-selected.jpg"]];
    
    UITabBarController *baseTabBarController = [[[UITabBarController alloc]init] autorelease];
    
    //    baseTabBarController.delegate=self;
    BOOL wasLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"wasLogin"];
    UITabBarItem *firsttab;
    if (wasLogin == NO) {
        firstView = [[[HomePageViewController alloc] init] autorelease];
        firsttab = [[[UITabBarItem alloc] initWithTitle:@"HOME" image:[UIImage imageNamed:@"ico-tab-home.png"] tag:0] autorelease];
        firstView.tabBarItem = firsttab;
    }
    else {
        firstView = [[[CallDoctorViewController alloc] init] autorelease];
        firsttab = [[[UITabBarItem alloc] initWithTitle:@"CALL DOCTOR" image:[UIImage imageNamed:@"ico-tab-call.png"] tag:0] autorelease];
        firstView.tabBarItem = firsttab;
    }
    HelpCenterViewController *helpView = [[[HelpCenterViewController alloc] init] autorelease];
    AHAHViewController *partnerView = [[[AHAHViewController alloc] init] autorelease];
    
    
    UITabBarItem *tabHelp = [[[UITabBarItem alloc] initWithTitle:@"HELP CENTER" image:[UIImage imageNamed:@"ico-tab-help.png"] tag:1] autorelease];
    UITabBarItem *tabPartners = [[[UITabBarItem alloc] initWithTitle:@"PARTNERS" image:[UIImage imageNamed:@"ico-tab-AHAH.png"] tag:2] autorelease];
    NSArray *controllers = [NSArray arrayWithObjects:firstView,helpView, partnerView, nil];
    //    NSArray *tabItems = [NSArray arrayWithObjects:tabHome, tabHelp, tabPartners, nil];
    
    helpView.tabBarItem = tabHelp;
    partnerView.tabBarItem = tabPartners;
    
    baseTabBarController.viewControllers = controllers;
    
    [[baseTabBarController tabBar] setBackgroundImage:[UIImage imageNamed:@"tab-background.jpg"]];
    
    self.window.rootViewController = baseTabBarController;
}

- (void)callSkypeWithName:(NSString *)nameCall
{
    if(isNetworkAvailable) {
        BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
        if(installed)
        {
            NSString *urlString = [NSString stringWithFormat:@"skype:%@?call", nameCall];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Skype application have not installed. Do you want install it now?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Install", nil];
            alertView.tag = 10000001;
            [alertView show];
            [alertView release];
            
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
        }
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)callGoogleHangoutWithEmail:(NSString *)emailCall
{
    if(isNetworkAvailable) {
        BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"com.google.hangouts:"]];
        if(installed)
        {
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"facetime://tel-number"]];
            NSString *urlString = [NSString stringWithFormat:@"com.google.hangouts://call?user=%@&video=true", emailCall];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Google hangouts application have not installed. Do you want install it now?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alertView.tag = 10000002;
            [alertView show];
            [alertView release];
            
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
        }
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

- (void)callFaceTimeWithEmail:(NSString *)emailCall
{
    if(isNetworkAvailable) {
        BOOL installed = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"facetime:"]];
        if(installed)
        {
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"facetime://tel-number"]];
            NSString *urlString = [NSString stringWithFormat:@"facetime:%@", emailCall];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Facetime application have not installed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/skype/skype"]];
        }
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
    }
}

#pragma mark - alertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if(alertView.tag == 10000001) {
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/app/skype/id304878510?mt=8"]];
            }
            else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/app/skype/id442012681?mt=8"]];
            }
        }
    }
}

#pragma mark -
#pragma mark - Check conection

- (void)registerToGetNetWorkStatus {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    Reachability *internetReach = [[Reachability reachabilityForInternetConnection] retain];
    [internetReach startNotifier];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if ((netStatus != ReachableViaWiFi && netStatus != ReachableViaWWAN)) {
        self.isNetworkAvailable = NO;
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alertView show];
//        [alertView release];
    }
    else {
        self.isNetworkAvailable = YES;
    }
}

- (void)reachabilityChanged:(NSNotification *)note {
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    if ((netStatus != ReachableViaWiFi && netStatus != ReachableViaWWAN)) {
        self.isNetworkAvailable = NO;
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No internet connections, please check your settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alertView show];
//        [alertView release];
    }
    else {
        self.isNetworkAvailable = YES;
    }
}
@end
